# -*- coding: utf-8 -*-
"""
十分简易的按行翻译脚本。
"""
import time
import random
import requests
import uuid

from requests.adapters import HTTPAdapter


def translate(query):
    """Azure翻译API"""
    # 设置你的key
    key = "0679f5e3457b48bfb7e70566451b143f"
    endpoint = "https://api.cognitive.microsofttranslator.com"
    constructed_url = endpoint + '/translate'
    params = {
        'api-version': '3.0',
        'from': 'en',
        'to': ['zh']
    }
    headers = {
        'Ocp-Apim-Subscription-Key': key,
        'Content-type': 'application/json',
        'X-ClientTraceId': str(uuid.uuid4())
    }
    body = [{'text': query}]
    time.sleep(random.randint(1, 3))
    request = requests.post(constructed_url, params=params, headers=headers, json=body, verify=False)
    sess = requests.Session()
    sess.mount('http://', HTTPAdapter(max_retries=3))
    sess.mount('https://', HTTPAdapter(max_retries=3))
    sess.keep_alive = False
    request.close()
    return request.json()


def read_file(filename):
    """ 读取待翻译的文件内容 """
    with open(filename, 'r') as f:
        content_list = f.readlines()
    return content_list


def translate_content(content, filename):
    """ 翻译内容并写入新TXT文件 """
    con = translate(query=content)
    print(con[0]['translations'][0]['text'])
    content = con[0]['translations'][0]['text']
    with open('{}.txt'.format(filename), 'a') as f:
        f.write(content)


def run():
    filename = 'iptables.txt'
    content_list = read_file(filename=filename)
    for content in content_list:
        translate_content(content, filename=filename)


run()
